<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>水平垂直居中示例</title>
<style>
  body, html {
    height: 100%;
    margin: 0;
  }
  section {
    margin: 20px;
    border: 1px solid #ccc;
    height: 150px;
    position: relative;
  }
  .box {
    background-color: #4caf50;
    color: white;
    width: 120px;
    height: 80px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 18px;
    border-radius: 8px;
  }

  /* 1. Flexbox 水平垂直居中 */
  .flexbox {
    display: flex;
    justify-content: center; /* 水平居中 */
    align-items: center;     /* 垂直居中 */
  }

  /* 2. Grid 水平垂直居中 */
  .grid {
    display: grid;
    place-items: center; /* 水平垂直居中 */
  }

  /* 3. 绝对定位 + transform */
  .absolute-parent {
    position: relative;
  }
  .absolute-child {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    background-color: #2196f3;
    color: white;
    width: 120px;
    height: 80px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 8px;
  }

  /* 4. table-cell 垂直居中 + text-align水平居中 */
  .table-parent {
    display: table;
    width: 100%;
    height: 150px;
  }
  .table-child {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
  }
  .table-box {
    display: inline-block;
    background-color: #ff5722;
    color: white;
    width: 120px;
    height: 80px;
    line-height: 80px;
    border-radius: 8px;
  }
</style>
</head>
<body>

<h1>水平垂直居中示例</h1>

<section class="flexbox">
  <div class="box">Flexbox</div>
</section>

<section class="grid">
  <div class="box">Grid</div>
</section>

<section class="absolute-parent">
  <div class="absolute-child">绝对定位</div>
</section>

<section class="table-parent">
  <div class="table-child">
    <div class="table-box">Table-cell</div>
  </div>
</section>

</body>
</html>
